package com.enjoy.redis.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("index")
public class IndexController {

    Logger logger = LoggerFactory.getLogger("enjoy");

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    Redisson redisson;

    @RequestMapping("reduceStock")
    public String reduceStock() {
        String lockKey = "lock";
//        while (true) {
//            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", 30, TimeUnit.SECONDS);
//            assert result != null;
//            if (result) {
//                break;
//            } else {
//                Thread.yield();
//            }
//        }
        RLock lock = redisson.getLock(lockKey);
        lock.lock();
        try {
            String stock = stringRedisTemplate.opsForValue().get("stock");
            stock = stock == null ? "0" : stock;
            int stockNum = Integer.parseInt(stock);
            if ((stockNum > 0)) {
                stockNum = stockNum - 1;
                stringRedisTemplate.opsForValue().set("stock", stockNum + "");
                logger.info("扣减库存成功，剩余：{}", stockNum);
            } else {
                logger.info("库存不足");
            }
        } finally {
//            stringRedisTemplate.delete(lockKey);
            lock.unlock();
        }
        return "success";
    }
}
